<template>
  <ContentWrap>
    <!-- 导航栏 -->
    <div class="navigation-bar">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item @click="navigateToPath('')" class="breadcrumb-item">
          根目录
        </el-breadcrumb-item>
        <el-breadcrumb-item
          v-for="(segment, index) in pathSegments"
          :key="index"
          @click="navigateToPath(getPathUpTo(index))"
          class="breadcrumb-item"
        >
          {{ segment }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <!-- <el-upload
        :action="uploadUrl"
        :data="{ path: currentPath }"
        :show-file-list="false"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :headers="uploadHeaders"
        multiple
      >
        <el-button type="primary"> <Icon icon="ep:upload" /> 上传文件 </el-button>
      </el-upload>
      <el-button @click="showCreateFolderDialog">
        <Icon icon="ep:folder-add" /> 新建文件夹
      </el-button> -->
      <el-button @click="getList"> <Icon icon="ep:refresh" /> 刷新 </el-button>
    </div>

    <!-- 文件列表 -->
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @row-dblclick="handleRowDoubleClick"
    >
      <el-table-column prop="name" label="名称" min-width="300">
        <template #default="{ row }">
          <div class="file-item" @click="handleFileClick(row)">
            <Icon :icon="getFileIcon(row)" class="file-icon" />
            <span class="file-name">{{ row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="size" label="大小" width="120">
        <template #default="{ row }">
          {{ row.isDirectory ? '-' : formatFileSize(row.size) }}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getTagType(row.type)">
            {{ getTypeLabel(row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="lastModified" label="修改时间" width="180">
        <template #default="{ row }">
          {{ row.lastModified ? formatDate(row.lastModified) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200px">
        <!-- <template #default="{ row }">
          <el-button
            v-if="!row.isDirectory && row.type !== 'parent'"
            link
            type="primary"
            @click="handleDownload(row)"
          >
            <Icon icon="ep:download" /> 下载
          </el-button>
          <el-button v-if="row.type !== 'parent'" link type="danger" @click="handleDelete(row)">
            <Icon icon="ep:delete" /> 删除
          </el-button>
        </template> -->
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <el-empty v-if="!loading && list.length === 0" description="暂无文件" />
  </ContentWrap>

  <!-- 创建文件夹对话框 -->
  <el-dialog v-model="createFolderVisible" title="新建文件夹" width="400px">
    <el-form :model="folderForm" label-width="80px">
      <el-form-item label="文件夹名">
        <el-input v-model="folderForm.name" placeholder="请输入文件夹名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="createFolderVisible = false">取消</el-button>
      <el-button type="primary" @click="handleCreateFolder">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAccessToken } from '@/utils/auth'
import { FileApi } from '@/api/agent/manage/file'

defineOptions({ name: 'FileManagement' })

// 文件信息接口
interface FileInfo {
  name: string
  path: string
  directory: boolean
  size: number
  lastModified: string
  type: string
}

const loading = ref(true)
const list = ref<FileInfo[]>([])
const currentPath = ref('')
const createFolderVisible = ref(false)
const folderForm = ref({ name: '' })

const uploadUrl = ref(FileApi.getUploadUrl())
const uploadHeaders = ref({
  Authorization: 'Bearer ' + getAccessToken()
})

// 路径分段
const pathSegments = computed(() => {
  return currentPath.value ? currentPath.value.split('/').filter(Boolean) : []
})

// 获取到指定索引的路径
const getPathUpTo = (index: number) => {
  return pathSegments.value.slice(0, index + 1).join('/')
}

/** 获取文件列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await FileApi.getFileList(currentPath.value)
    list.value = res || []
  } catch (error) {
    ElMessage.error('获取文件列表失败')
    console.error('获取文件列表失败:', error)
  } finally {
    loading.value = false
  }
}

/** 导航到指定路径 */
const navigateToPath = (path: string) => {
  currentPath.value = path
  getList()
}

/** 文件点击处理 */
const handleFileClick = (file: FileInfo) => {
  if (file.directory) {
    if (file.type === 'parent') {
      navigateToPath(file.path)
    } else {
      navigateToPath(file.path)
    }
  }
}

/** 双击行处理 */
const handleRowDoubleClick = (row: FileInfo) => {
  handleFileClick(row)
}

/** 显示创建文件夹对话框 */
const showCreateFolderDialog = () => {
  folderForm.value.name = ''
  createFolderVisible.value = true
}

/** 创建文件夹 */
const handleCreateFolder = async () => {
  if (!folderForm.value.name.trim()) {
    ElMessage.warning('请输入文件夹名称')
    return
  }

  try {
    await FileApi.createFolder(folderForm.value.name, currentPath.value)
    ElMessage.success('文件夹创建成功')
    createFolderVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error('创建文件夹失败')
    console.error('创建文件夹失败:', error)
  }
}

/** 上传成功回调 */
const handleUploadSuccess = (response: any) => {
  if (response.code === 0) {
    ElMessage.success('文件上传成功')
    getList()
  } else {
    ElMessage.error(response.msg || '文件上传失败')
  }
}

/** 上传失败回调 */
const handleUploadError = (error: any) => {
  ElMessage.error('文件上传失败: ' + error.message)
  console.error('文件上传失败:', error)
}

/** 下载文件 */
const handleDownload = (file: FileInfo) => {
  const downloadUrl = FileApi.getDownloadUrl(file.name, currentPath.value)
  window.open(downloadUrl, '_blank')
  ElMessage.success(`开始下载文件: ${file.name}`)
}

/** 删除文件 */
const handleDelete = async (file: FileInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除${file.isDirectory ? '文件夹' : '文件'} "${file.name}" 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await FileApi.deleteFile(file.path)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  }
}

/** 获取文件图标 */
const getFileIcon = (file: FileInfo) => {
  if (file.type === 'parent') return 'ep:back'
  if (file.directory) return 'ep:folder'

  const iconMap: Record<string, string> = {
    pdf: 'ep:document',
    doc: 'ep:document',
    docx: 'ep:document',
    xls: 'ep:document',
    xlsx: 'ep:document',
    ppt: 'ep:document',
    pptx: 'ep:document',
    txt: 'ep:document',
    md: 'ep:document',
    jpg: 'ep:picture',
    jpeg: 'ep:picture',
    png: 'ep:picture',
    gif: 'ep:picture',
    svg: 'ep:picture',
    mp4: 'ep:video-play',
    avi: 'ep:video-play',
    mov: 'ep:video-play',
    mp3: 'ep:headphones',
    wav: 'ep:headphones',
    zip: 'ep:box',
    rar: 'ep:box',
    '7z': 'ep:box'
  }

  return iconMap[file.type] || 'ep:document'
}

/** 获取标签类型 */
const getTagType = (type: string) => {
  if (type === 'folder' || type === 'parent') return 'primary'
  return 'info'
}

/** 获取类型标签 */
const getTypeLabel = (file: FileInfo) => {
  if (file.type === 'parent') return '上级目录'
  if (file.isDirectory) return '文件夹'
  return file.type
}

/** 格式化文件大小 */
const formatFileSize = (bytes: number) => {
  if (!bytes || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/** 格式化日期 */
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.navigation-bar {
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .breadcrumb-item {
    cursor: pointer;
    &:hover {
      color: #409eff;
    }
  }
}

.toolbar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.file-item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;

  .file-icon {
    font-size: 18px;
    color: #409eff;
  }

  .file-name {
    color: #303133;
    font-weight: 500;
  }

  &:hover .file-name {
    color: #409eff;
  }
}

:deep(.el-table) {
  .el-table__row {
    cursor: pointer;

    &:hover {
      .file-name {
        color: #409eff;
      }
    }
  }
}
</style>
